<?php

namespace app\admin\controller\vactivities;


use app\admin\model\Conference;
use app\common\controller\Backend;
use app\common\controller\Callfunc;
use app\common\library\Iden;
use Exception;
use think\Db;
use app\admin\model\vactivities\Ticket;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Session;


/**
 * 活动管理
 *
 * @icon fa fa-circle-o
 */
class Activity extends Backend
{
    
    /**
     * Activity模型对象
     * @var \app\admin\model\vactivities\Activity
     */
    protected $model = null;
    private $catemodel = null;
    private $tagsmodel = null;
    private $tmodel = null;
    private $seriesmodel = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\vactivities\Activity;
        $this->view->assign("isrecordingList", $this->model->getIsrecordingList());
        $this->catemodel = new \app\admin\model\superdata\Activitycategory;
        $this->tagsmodel = new \app\admin\model\superdata\Activitytags;
        $this->tmodel = new \app\admin\model\vactivities\Ticket;
        $this->seriesmodel = new \app\admin\model\vactivities\Seriesactivity;
        $this->view->assign('categoryList',$this->catemodel->getCategoryList());
        //print_R($this->tagsmodel->getAtagsList());die;
        $this->view->assign('AtagsList',$this->tagsmodel->getAtagsList());
        $this->view->assign('seriesList',$this->seriesmodel->getSeriesList($this->auth->id));

        $this->view->assign('headingList', $this->model->getHeadingList(1));
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        $mywhere['admin_id'] = $this->auth->id;
        $tag = $this->request->param('tag');
        $nowTime = time();
        if(!empty($tag)){
            if($tag == $this->model::ACTIVITY_TAG_1){
              //  $map = ['startTime'=>['gt',$nowTime],'status'=>['neq',2]];//<=
                $map = " (startTime+duration) > $nowTime and status <> 2";
            }else if($tag == $this->model::ACTIVITY_TAG_2){
                //$map = ['startTime'=>['elt',$nowTime],'status'=>['neq',2]];//>
                $map = " (startTime+duration) <= $nowTime and status <> 2";
            }else if ($tag == $this->model::ACTIVITY_TAG_3){//回收站
               // $map = ['status'=>['eq',2]];
                $map = "  status = 2";
            }
        }else{
            $tag = 1;
           // $map = ['startTime'=>['gt',$nowTime],'status'=>['neq',2]];
            $map = " (startTime+duration) > $nowTime and status <> 2";
        }

        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where($map)
                ->where($mywhere)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->where($where)
                ->where($map)
                ->where($mywhere)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $row) {
                $row['tags'] = $this->tagsmodel->getTagsNameById($row['tags']);
                $row['category'] = $this->catemodel->getcateNameById($row['category']);
                $row['series_id'] = $this->seriesmodel->getseriesNameById($row['series_id']);
                $row['duration'] = s_to_hs($row['duration']);
                $row['nowTime'] = $nowTime;//自定义一个当前时间
            }

            $list = collection($list)->toArray();
            if (!empty($list)){
                $sessionId = session_id();
                $adminInfo = Db::name('admin')->field('nickname, serial, token')->where('id', $this->auth->id)->find();

                $confModel = new Conference();
                $userToken = $confModel->getUserToken($this->auth->id, $adminInfo['token']);

                $displayName = $adminInfo['nickname'];
                $peerName = $adminInfo['serial'];
                foreach ($list as &$rs) {
                    $roomUrl = config('join_room_url') . "?m={$rs['serial']}&peerName={$peerName}&displayName={$displayName}&PHPSESSID={$sessionId}&token={$userToken}";
                    $rs['joinUrl'] = $roomUrl;
                }
                unset($rs);
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }

        $this->view->assign('now_function', 'vactivities/activity/index');
        $this->view->assign("tag", $tag);
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
           // print_R($params);die;
            $params['admin_id'] = $this->auth->id;
            //$params['serial'] = getRandomString(8);
            //$params['serial'] = nonceStr();
            $params['serial'] = Callfunc::makeUuid();     //---  生成唯一识别码

            if($params['duration']==0){
                $this->error(__('时长不能为0'));
            }
            $params['duration'] = (int)$params['duration'] * 60;
            $params['startTime'] = strtotime($params['startTime']);
            $params['endTime'] = $params['duration'] + $params['startTime'];
            $params['link_url'] = trim($params['link_url']);
            $tmodel = new \app\admin\model\vactivities\Ticket;
            //$params['endTime'] = 0;
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                $t = [];
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    $count = count(array_filter($params['ticket_name']));
                    if($count == 0){
                        $count = count(array_filter($params['ticket_price']));
                    }
                    //同步到会议表（基本信息）
                    $conModel = new Conference();
                    $res = $conModel->addConference($params);
                    if($count > 0){//添加入场卷
                        for($i = 0;$i < $count;$i++){
//                            if($params['ticket_price'][$i]==0 || $params['ticket_price'][$i]==0.00){
//                                $params['ticket_name'][$i] = 'VIP入场券';
//                            }
                            $t[] = [
                                'name'=> isset($params['ticket_name'][$i]) ? $params['ticket_name'][$i]:'',
                                'price'=> priceyuantofen($params['ticket_price'][$i]),
                                'number'=>$params['ticket_number'][$i],
                                'temp'=>$params['ticket_number'][$i],//余额
                                'activity_id'=>$this->model->id,
                                'type'=>Ticket::TICKET_TYPE_2,
                                'admin_id'=>$this->auth->id,
                                'createTime' => date('Y-m-d H:i:s',time()),
                                'temp'=>$params['ticket_number'][$i],
                                'start_time'=>time(),
                                'end_time'=>$params['endTime'],
                                'ticket_type'=>$params['Isticket'],
                            ];

                        }
                        $count = count(array_filter($t));
                        if($count > 0 ){
                            $this->tmodel->insetAll($t);
                        }
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);

        $row['duration'] = s_to_hs($row['duration']);
        $row['startTime'] = date('Y-m-d H:i:s',$row['startTime']);
        $tmodel = new \app\admin\model\vactivities\Ticket;
        $tlist = $tmodel->getTicketList($ids,Ticket::TICKET_TYPE_2,'');
        $row['tlist'] = isset($tlist) ? json_encode($tlist, JSON_UNESCAPED_UNICODE) : '';
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params) {
                $params = $this->preExcludeFields($params);
                $params['duration'] = (int)$params['duration'] * 60;
                $params['startTime'] = strtotime($params['startTime']);
                $params['endTime'] = $params['duration'] + $params['startTime'];
                $params['link_url'] = trim($params['link_url']);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    $series_id = isset($params['series_id']) && $params['series_id'] > 0 ? 1:2;
                    $result = $row->allowField(true)->save($params);


                    //同步到会议表（基本信息）
                    $conModel = new Conference();
                    $params['admin_id'] = $this->auth->id;
                    $res = $conModel->addConference($params,1);//修改


                    $tArr = $tmodel->getTicketByActId($params['id'],$series_id);//查找活动下的入场卷
                    $tnArr = [];
                    if(!empty($params['ticket_name']) || !empty($params['ticket_price'])){//添加入场卷
                        $count = count($params['ticket_name']);
                        if($count == 0){
                            $count = count($params['ticket_price']);
                        }
                        for($i = 0;$i < $count;$i++){
//                            if($params['ticket_price'][$i]==0 || $params['ticket_price'][$i]==0.00){
//                                $params['ticket_name'][$i] = 'VIP入场券';
//                            }

                            if(!empty($params['ticket_id'][$i])){//获取到入场卷id则更新
                                $rs = $tmodel->findId($params['ticket_id'][$i]);
                                if($rs){
                                    $u[]=[
                                        'id' =>$params['ticket_id'][$i],
                                        'name'=>$params['ticket_name'][$i],
                                        'price'=>priceyuantofen($params['ticket_price'][$i]),
                                        'number'=>$params['ticket_number'][$i],
                                        'temp'=>$params['ticket_number'][$i],
                                        'activity_id'=>$params['id'],
                                        'type'=>Ticket::TICKET_TYPE_2,
                                        'admin_id'=>$this->auth->id,
                                        'updateTime' => date('Y-m-d H:i:s',time()),
                                        'temp'=>$params['ticket_number'][$i],
                                        'start_time'=>time(),
                                        'end_time'=>$params['endTime'],
                                        'ticket_type'=>$params['isticket'],
                                    ];
                                    $tnArr[] = $params['ticket_id'][$i];//只获取查找到的入场卷id
                                }
                            }else{
                                $t[] = [
                                    'name'=>$params['ticket_name'][$i],
                                    'price'=>priceyuantofen($params['ticket_price'][$i]),
                                    'number'=>$params['ticket_number'][$i],
                                    'activity_id'=>$params['id'],
                                    'type'=>Ticket::TICKET_TYPE_2,
                                    'admin_id'=>$this->auth->id,
                                    'createTime' => date('Y-m-d H:i:s',time()),
                                    'temp'=>$params['ticket_number'][$i],
                                    'start_time'=>time(),
                                    'end_time'=>$params['endTime'],
                                    'ticket_type'=>$params['isticket'],
                                ];
                            }
                        }

                        if(isset($t)){//批量插入
                            $tmodel->insetAll($t);
                        }
                        if(isset($u)){//批量更新
                            $tmodel->updataAll($u);
                        }
                    }

                    if(!empty($tArr)){//查找俩数组中不同元素
                        $tmodel->delAll($tArr,$tnArr);
                    }
                    Db::commit();
                    unset($u);
                    unset($t);
                    unset($tArr);
                    unset($tnArr);

                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
      //  print_r($row);die;
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public function detail()
    {

        $ids = $this->request->param("ids");
        $state = input('status/d');
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if(is_array($adminIds)){
            if (!in_array($row[$this->dataLimitField],$adminIds)){
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isAjax()) {
            if ($state == $this->model::ACTIVITY_STATUS_1){
                $state = $this->model::ACTIVITY_STATUS_0;
            }else {
                $state = $this->model::ACTIVITY_STATUS_1;
            }


            Db::name('activity')->where('id',$ids)->update(['status'=>$state]);
            $this->success("Ajax请求成功", null, ['id' => $ids]);
        }
       // print_R($row->toArray());die;
        $row = $row->toArray();
        $tagsmodel = new  \app\admin\model\superdata\Activitytags;
        $catemodel = new  \app\admin\model\superdata\Activitycategory;
        $seriesemodel = new  \app\admin\model\vactivities\Seriesactivity;
        $row['tags'] = $tagsmodel->getTagsNameById($row['tags']);
        $row['category'] = !empty($row['category']) ? $catemodel->getcateNameById($row['category']):'--';
        $row['series_id'] = !empty($row['series_id']) ? $seriesemodel->getseriesNameById($row['series_id']):'--';
        $row['duration'] = s_to_hs($row['duration']);
        $row['startTime'] = date('Y-m-d H:i:s',$row['startTime']);
        $row['isrecording'] = $row['isrecording'] == 0 ? '否':'是';
        $row['thumb'] = explode(',',$row['thumb']);
        $tmodel = new \app\admin\model\vactivities\Ticket;
        $tlist = $tmodel->getTicketList($ids,Ticket::TICKET_TYPE_2,'');
        $row['tlist'] = isset($tlist) ? $tlist : '';
      //  print_r($row);die;
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /*
     * 还原与彻底删除
     */
    public function recyAndDelete(){
        $ids = $this->request->param("ids");
        $state = input('pack_id/d');
        $row = $this->model->get(['id' => $ids]);

        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $adminIds = $this->getDataLimitAdminIds();
        if(is_array($adminIds)){
            if (!in_array($row[$this->dataLimitField],$adminIds)){
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isAjax()) {
            $rs = $row->toArray();
            switch ($state) {
                case 1://还原
                    Db::name('activity')->where('id',$ids)->update(['status'=>$this->model::ACTIVITY_STATUS_1]);
                    break;
                case 2://删除
                    Db::name('activity')->where('id',$ids)->update(['status'=>$this->model::ACTIVITY_STATUS_2,'delTime'=>time()]);
                    break;
                case 3://彻底删除
                    Db::name('activity')->where('id',$ids)->delete();
                    break;
                default:
                    break;
            }

            $this->success("Ajax请求成功", null, ['id' => $ids]);
        }

    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                   // $count += $v->update(['status'=>$this->model::ACTIVITY_STATUS_2]);

                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }


    /**
     * 回收站
     */
    public function recyclebin()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->onlyTrashed()
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    public function test(){
      // $rs =  Dbb::getTeachersList();
       $s =  new \app\common\model\Dbb;
       $rs = $s->test();
       //$rs = Dbb::test3();
       print_r($rs);
       echo 'ddd';die;
       return $rs;
    }

    /*
     * 推荐功能
     */
    public function recommend(){
        $ids = $this->request->param("ids");
        $isrecommend = input('isrecommend/d');
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if(is_array($adminIds)){
            if (!in_array($row[$this->dataLimitField],$adminIds)){
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isAjax()) {
            if ($isrecommend == $this->model::ACTIVITY_STATUS_1){
                $isrecommend = $this->model::ACTIVITY_STATUS_0;
            }else {
                $isrecommend = $this->model::ACTIVITY_STATUS_1;
            }

             Db::name('activity')->where('id',$ids)->update(['isrecommend'=>$isrecommend]);
            }
            $this->success("Ajax请求成功", null, ['id' => $ids]);
     }

    /*
  * 复制
  */
    public function copy(){
        $ids = $this->request->param("ids");
       // $ids=  Iden::decrypt($ids);
        $row = $this->model->get(['id' => $ids]);

        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row = $row->toArray();
       // print_r($row);die;
        try {
            if($row){
                $t[] = [
                    'name' =>$row['name'],
                    'serial'=>getRandomString(8),
                    'thumb'=>$row['thumb'],
                    'summary'=>$row['summary'],
                    'detail' =>$row['detail'],
                    'createTime'=>$row['createTime'],
                    'startTime'=>$row['startTime'],
                    'duration'=>$row['duration'],
                    'category'=>$row['category'],
                    'tags'=>$row['tags'],
                    'isrecording'=>$row['isrecording'],
                    'series_id'=>$row['series_id'],
                    'admin_id'=>$this->auth->id,
                    'status'=>$row['status'],
                    'collection'=>$row['collection'],
                    'share'=>$row['share'],
                    'operate_id'=>$row['operate_id'],
                    'endTime'=>$row['endTime'],
                    'isend'=>$row['isend'],
                    'link_url'=>$row['link_url'],
                    'delTime'=>0,
                ];
                Db::name('activity')->insertAll($t);
            }
        } catch (PDOException $e) {

            $this->error($e->getMessage());
        } catch (Exception $e) {

            $this->error($e->getMessage());
        }
        $this->success("复制成功", null, ['id' => $ids]);
    }
}
